﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vit.Common;
using Vit.Common.Extensions;

namespace Vit.SchemaExplorer
{
    [Serializable]
    public abstract class SchemaObjectBase
    {
        public SchemaObjectBase()
        {
            ExtendedProperties = new List<Tuple<string, object>>();
        }

        public object GetExtendedProperty(string name)
        {
            if (ExtendedProperties != null)
            {
                var prop = ExtendedProperties.FirstOrDefault(o => o.Item1.Equals(name, StringComparison.OrdinalIgnoreCase));
                if (prop != null)
                    return prop.Item2;
            }
            return null;
        }

        public T GetExtendedProperty<T>(string name)
        {
            return GetExtendedProperty<T>(name, default(T));
        }

        public T GetExtendedProperty<T>(string name, T defaultValue)
        {
            object val = GetExtendedProperty(name);
            if (val == null)
                return defaultValue;
            return val.ConvertTo<T>(defaultValue);
        }

        public void SetExtendedProperty(string name, object value)
        {
            if (ExtendedProperties == null)
                ExtendedProperties = new List<Tuple<string, object>>();

            var prop = ExtendedProperties.FirstOrDefault(o => o.Item1.Equals(name, StringComparison.OrdinalIgnoreCase));
            if (prop != null)
                ExtendedProperties.Remove(prop);

            prop = new Tuple<string, object>(name, value);
            ExtendedProperties.Add(prop);
        }

        public virtual string Owner { get; set; }
        public virtual string Name { get; set; }
        public virtual string Description { get; set; }
        public virtual string FullName 
        {
            get
            {
                return this.Schema.Database.SchemaProvider.BuildFullName(this.Schema.Name, this.Owner, this.Name);
            }
        }
        public virtual string SafeName
        {
            get
            {
                return this.Schema.Database.SchemaProvider.BuildSafeName(this.Name);
            }
        }

        public virtual List<Tuple<string, object>> ExtendedProperties { get; set; }

        [System.Xml.Serialization.XmlIgnore()]
        [System.Xml.Serialization.SoapIgnore()]
        public virtual SchemaSchema Schema { get; set; }
    }
}
